[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import { isIPageInfoForEntity } from '@growi/core';
  4. import type {
  5. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  6. } from '@growi/core';
  7. import {
  8. isClient, pagePathUtils, pathUtils,
  9. } from '@growi/core/dist/utils';
  10. import ExtensibleCustomError from 'extensible-custom-error';
  11. import type {
  12. GetServerSideProps, GetServerSidePropsContext,
  13. } from 'next';
  14. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  15. import dynamic from 'next/dynamic';
  16. import Head from 'next/head';
  17. import { useRouter } from 'next/router';
  18. import superjson from 'superjson';
  19. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  20. import { PageView } from '~/components/Page/PageView';
  21. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript'; import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { PageModel, PageDocument } from '~/server/models/page';
  26. import type { PageRedirectModel } from '~/server/models/page-redirect';
  27. import {
  28. useCurrentUser,
  29. useIsForbidden, useIsSharedUser,
  30. useIsEnabledStaleNotification, useIsIdenticalPath,
  31. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  32. useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  33. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  34. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  35. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  36. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  37. } from '~/stores/context';
  38. import { useEditingMarkdown } from '~/stores/editor';
  39. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  40. import {
  41. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  42. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  43. } from '~/stores/page';
  44. import { useRedirectFrom } from '~/stores/page-redirect';
  45. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  46. import { useSelectedGrant } from '~/stores/ui';
  47. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  48. import loggerFactory from '~/utils/logger';
  49. import { BasicLayout } from '../components/Layout/BasicLayout';
  50. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  51. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  52. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  53. import type { NextPageWithLayout } from './_app.page';
  54. import type { CommonProps } from './utils/commons';
  55. import {
  56. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR,
  57. } from './utils/commons';
  58. declare global {
  59. // eslint-disable-next-line vars-on-top, no-var
  60. var globalEmitter: EventEmitter;
  61. }
  62. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  63. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  64. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  65. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  66. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  67. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  68. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  69. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  70. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  71. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  72. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  73. const logger = loggerFactory('growi:pages:all');
  74. const {
  75. isPermalink: _isPermalink, isCreatablePage,
  76. } = pagePathUtils;
  77. const { removeHeadingSlash } = pathUtils;
  78. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  79. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  80. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  81. {
  82. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  83. return v?.data != null
  84. && v?.data.toObject != null
  85. && v?.meta != null
  86. && isIPageInfoForEntity(v.meta);
  87. },
  88. serialize: (v) => {
  89. return {
  90. data: superjson.stringify(v.data.toObject()),
  91. meta: superjson.stringify(v.meta),
  92. };
  93. },
  94. deserialize: (v) => {
  95. return {
  96. data: superjson.parse(v.data),
  97. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  98. };
  99. },
  100. },
  101. 'IPageToShowRevisionWithMetaTransformer',
  102. );
  103. // GrowiContextualSubNavigation for NOT shared page
  104. type GrowiContextualSubNavigationProps = {
  105. isLinkSharingDisabled: boolean,
  106. }
  107. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  108. const { isLinkSharingDisabled } = props;
  109. const { data: currentPage } = useSWRxCurrentPage();
  110. return (
  111. <div data-testid="grw-contextual-sub-nav">
  112. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  113. </div>
  114. );
  115. };
  116. type Props = CommonProps & {
  117. pageWithMeta: IPageToShowRevisionWithMeta | null,
  118. // pageUser?: any,
  119. redirectFrom?: string;
  120. // shareLinkId?: string;
  121. isLatestRevision?: boolean,
  122. isIdenticalPathPage?: boolean,
  123. isForbidden: boolean,
  124. isNotFound: boolean,
  125. isNotCreatable: boolean,
  126. // isAbleToDeleteCompletely: boolean,
  127. templateTagData?: string[],
  128. templateBodyData?: string,
  129. isSearchServiceConfigured: boolean,
  130. isSearchServiceReachable: boolean,
  131. isSearchScopeChildrenAsDefault: boolean,
  132. isEnabledMarp: boolean,
  133. isSlackConfigured: boolean,
  134. // isMailerSetup: boolean,
  135. isAclEnabled: boolean,
  136. // hasSlackConfig: boolean,
  137. drawioUri: string | null,
  138. hackmdUri: string,
  139. noCdn: string,
  140. // highlightJsStyle: string,
  141. isAllReplyShown: boolean,
  142. isContainerFluid: boolean,
  143. editorConfig: EditorConfig,
  144. isEnabledStaleNotification: boolean,
  145. isEnabledAttachTitleHeader: boolean,
  146. // isEnabledLinebreaks: boolean,
  147. // isEnabledLinebreaksInComments: boolean,
  148. adminPreferredIndentSize: number,
  149. isIndentSizeForced: boolean,
  150. disableLinkSharing: boolean,
  151. skipSSR: boolean,
  152. ssrMaxRevisionBodyLength: number,
  153. grantData?: IPageGrantData,
  154. rendererConfig: RendererConfig,
  155. };
  156. const Page: NextPageWithLayout<Props> = (props: Props) => {
  157. // register global EventEmitter
  158. if (isClient() && window.globalEmitter == null) {
  159. window.globalEmitter = new EventEmitter();
  160. }
  161. const router = useRouter();
  162. useCurrentUser(props.currentUser ?? null);
  163. // commons
  164. useEditorConfig(props.editorConfig);
  165. useCsrfToken(props.csrfToken);
  166. useGrowiCloudUri(props.growiCloudUri);
  167. // page
  168. useIsContainerFluid(props.isContainerFluid);
  169. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  170. useIsForbidden(props.isForbidden);
  171. useIsNotCreatable(props.isNotCreatable);
  172. useRedirectFrom(props.redirectFrom ?? null);
  173. useIsSharedUser(false); // this page cann't be routed for '/share'
  174. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  175. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  176. useIsSearchPage(false);
  177. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  178. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  179. useIsSearchServiceReachable(props.isSearchServiceReachable);
  180. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  181. useIsSlackConfigured(props.isSlackConfigured);
  182. // useIsMailerSetup(props.isMailerSetup);
  183. useIsAclEnabled(props.isAclEnabled);
  184. // useHasSlackConfig(props.hasSlackConfig);
  185. useHackmdUri(props.hackmdUri);
  186. // useNoCdn(props.noCdn);
  187. useDefaultIndentSize(props.adminPreferredIndentSize);
  188. useIsIndentSizeForced(props.isIndentSizeForced);
  189. useDisableLinkSharing(props.disableLinkSharing);
  190. useRendererConfig(props.rendererConfig);
  191. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  192. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  193. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  194. useIsAllReplyShown(props.isAllReplyShown);
  195. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  196. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  197. const { pageWithMeta } = props;
  198. const pageId = pageWithMeta?.data._id;
  199. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  200. const revisionBody = pageWithMeta?.data.revision?.body;
  201. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  202. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  203. useCurrentPathname(props.currentPathname);
  204. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  205. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  206. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  207. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  208. const { mutate: mutateIsNotFound } = useIsNotFound();
  209. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  210. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  211. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  212. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  213. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  214. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  215. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  216. useSetupGlobalSocket();
  217. useSetupGlobalSocketForPage(pageId);
  218. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  219. // Store initial data (When revisionBody is not SSR)
  220. useEffect(() => {
  221. if (!props.skipSSR) {
  222. return;
  223. }
  224. if (currentPageId != null && !props.isNotFound) {
  225. const mutatePageData = async() => {
  226. const pageData = await mutateCurrentPage();
  227. mutateEditingMarkdown(pageData?.revision.body);
  228. };
  229. // If skipSSR is true, use the API to retrieve page data.
  230. // Because pageWIthMeta does not contain revision.body
  231. mutatePageData();
  232. }
  233. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  234. // sync grant data
  235. useEffect(() => {
  236. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  237. mutateSelectedGrant(grantDataToApply);
  238. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  239. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  240. useEffect(() => {
  241. const decodedURI = decodeURI(window.location.pathname);
  242. if (isClient() && decodedURI !== props.currentPathname) {
  243. const { search, hash } = window.location;
  244. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  245. }
  246. }, [props.currentPathname, router]);
  247. // initialize mutateEditingMarkdown only once per page
  248. // need to include useCurrentPathname not useCurrentPagePath
  249. useEffect(() => {
  250. if (props.currentPathname != null) {
  251. mutateEditingMarkdown(revisionBody);
  252. }
  253. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  254. useEffect(() => {
  255. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  256. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  257. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  258. useEffect(() => {
  259. mutateCurrentPageId(pageId ?? null);
  260. }, [mutateCurrentPageId, pageId]);
  261. useEffect(() => {
  262. mutateIsNotFound(props.isNotFound);
  263. }, [mutateIsNotFound, props.isNotFound]);
  264. useEffect(() => {
  265. mutateIsLatestRevision(props.isLatestRevision);
  266. }, [mutateIsLatestRevision, props.isLatestRevision]);
  267. useEffect(() => {
  268. mutateTemplateTagData(props.templateTagData);
  269. }, [props.templateTagData, mutateTemplateTagData]);
  270. useEffect(() => {
  271. mutateTemplateBodyData(props.templateBodyData);
  272. }, [props.templateBodyData, mutateTemplateBodyData]);
  273. const title = generateCustomTitleForPage(props, pagePath);
  274. return (
  275. <>
  276. <Head>
  277. <title>{title}</title>
  278. </Head>
  279. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  280. <header className="py-0 position-relative">
  281. <div id="grw-subnav-container">
  282. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  283. </div>
  284. </header>
  285. <div className="d-edit-none">
  286. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  287. </div>
  288. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  289. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  290. <DisplaySwitcher
  291. pageView={
  292. <PageView
  293. pagePath={pagePath}
  294. initialPage={pageWithMeta?.data}
  295. rendererConfig={props.rendererConfig}
  296. />
  297. }
  298. />
  299. <PageStatusAlert />
  300. </div>
  301. </>
  302. );
  303. };
  304. type LayoutProps = Props & {
  305. children?: ReactNode
  306. }
  307. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  308. const className = useEditorModeClassName();
  309. // init sidebar config with UserUISettings and sidebarConfig
  310. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  311. return (
  312. <BasicLayout className={className}>
  313. {children}
  314. </BasicLayout>
  315. );
  316. };
  317. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  318. return (
  319. <>
  320. <GrowiPluginsActivator />
  321. <DrawioViewerScript />
  322. <Layout {...page.props}>
  323. {page}
  324. </Layout>
  325. <UnsavedAlertDialog />
  326. <DescendantsPageListModal />
  327. <DrawioModal />
  328. <HandsontableModal />
  329. <QuestionnaireModalManager />
  330. <TemplateModal />
  331. <LinkEditModal />
  332. </>
  333. );
  334. };
  335. function getPageIdFromPathname(currentPathname: string): string | null {
  336. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  337. }
  338. class MultiplePagesHitsError extends ExtensibleCustomError {
  339. pagePath: string;
  340. constructor(pagePath: string) {
  341. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  342. this.pagePath = pagePath;
  343. }
  344. }
  345. // apply parent page grant fot creating page
  346. async function applyGrantToPage(props: Props, ancestor: any) {
  347. await ancestor.populate('grantedGroup');
  348. const grant = {
  349. grant: ancestor.grant,
  350. };
  351. const grantedGroup = ancestor.grantedGroup ? {
  352. grantedGroup: {
  353. id: ancestor.grantedGroup.id,
  354. name: ancestor.grantedGroup.name,
  355. },
  356. } : {};
  357. props.grantData = Object.assign(grant, grantedGroup);
  358. }
  359. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  360. const { model: mongooseModel } = await import('mongoose');
  361. const req: CrowiRequest = context.req as CrowiRequest;
  362. const { crowi } = req;
  363. const { revisionId } = req.query;
  364. const Page = crowi.model('Page') as PageModel;
  365. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  366. const { pageService, configManager } = crowi;
  367. let currentPathname = props.currentPathname;
  368. const pageId = getPageIdFromPathname(currentPathname);
  369. const isPermalink = _isPermalink(currentPathname);
  370. const { user } = req;
  371. if (!isPermalink) {
  372. // check redirects
  373. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  374. if (chains != null) {
  375. // overwrite currentPathname
  376. currentPathname = chains.end.toPath;
  377. props.currentPathname = currentPathname;
  378. // set redirectFrom
  379. props.redirectFrom = chains.start.fromPath;
  380. }
  381. // check whether the specified page path hits to multiple pages
  382. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  383. if (count > 1) {
  384. throw new MultiplePagesHitsError(currentPathname);
  385. }
  386. }
  387. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  388. const page = pageWithMeta?.data as unknown as PageDocument;
  389. // add user to seen users
  390. if (page != null && user != null) {
  391. await page.seen(user);
  392. }
  393. // populate & check if the revision is latest
  394. if (page != null) {
  395. page.initLatestRevisionField(revisionId);
  396. props.isLatestRevision = page.isLatestRevision();
  397. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  398. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  399. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  400. }
  401. if (page == null && user != null) {
  402. const templateData = await Page.findTemplate(props.currentPathname);
  403. if (templateData != null) {
  404. props.templateTagData = templateData.templateTags as string[];
  405. props.templateBodyData = templateData.templateBody as string;
  406. }
  407. // apply pagrent page grant
  408. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  409. if (ancestor != null) {
  410. await applyGrantToPage(props, ancestor);
  411. }
  412. }
  413. props.pageWithMeta = pageWithMeta;
  414. }
  415. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  416. const req: CrowiRequest = context.req as CrowiRequest;
  417. const { crowi } = req;
  418. const Page = crowi.model('Page') as PageModel;
  419. const { currentPathname } = props;
  420. const pageId = getPageIdFromPathname(currentPathname);
  421. const isPermalink = _isPermalink(currentPathname);
  422. const page = props.pageWithMeta?.data;
  423. if (props.isIdenticalPathPage) {
  424. props.isNotCreatable = true;
  425. }
  426. else if (page == null) {
  427. props.isNotFound = true;
  428. props.isNotCreatable = !isCreatablePage(currentPathname);
  429. // check the page is forbidden or just does not exist.
  430. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  431. props.isForbidden = count > 0;
  432. }
  433. else {
  434. props.isNotFound = page.isEmpty;
  435. props.isNotCreatable = false;
  436. props.isForbidden = false;
  437. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  438. if (isPermalink && page.isEmpty) {
  439. props.currentPathname = page.path;
  440. }
  441. // /path/to/page ==> /62a88db47fed8b2d94f30000
  442. if (!isPermalink && !page.isEmpty) {
  443. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  444. if (!isToppage) {
  445. props.currentPathname = `/${page._id}`;
  446. }
  447. }
  448. }
  449. }
  450. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  451. // const req: CrowiRequest = context.req as CrowiRequest;
  452. // const { crowi } = req;
  453. // const UserModel = crowi.model('User');
  454. // if (isUserPage(props.currentPagePath)) {
  455. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  456. // if (user != null) {
  457. // props.pageUser = JSON.stringify(user.toObject());
  458. // }
  459. // }
  460. // }
  461. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  462. const req: CrowiRequest = context.req as CrowiRequest;
  463. const { crowi } = req;
  464. const {
  465. searchService, configManager, aclService,
  466. } = crowi;
  467. props.isSearchServiceConfigured = searchService.isConfigured;
  468. props.isSearchServiceReachable = searchService.isReachable;
  469. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  470. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  471. // props.isMailerSetup = mailService.isMailerSetup;
  472. props.isAclEnabled = aclService.isAclEnabled();
  473. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  474. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  475. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  476. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  477. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  478. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  479. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  480. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  481. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  482. props.editorConfig = {
  483. upload: {
  484. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  485. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  486. },
  487. };
  488. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  489. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  490. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  491. props.rendererConfig = {
  492. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  493. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  494. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  495. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  496. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  497. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  498. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  499. // XSS Options
  500. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  501. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  502. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  503. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  504. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  505. };
  506. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  507. }
  508. /**
  509. * for Server Side Translations
  510. * @param context
  511. * @param props
  512. * @param namespacesRequired
  513. */
  514. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  515. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  516. props._nextI18Next = nextI18NextConfig._nextI18Next;
  517. }
  518. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  519. const req = context.req as CrowiRequest<IUserHasId & any>;
  520. const { user } = req;
  521. const result = await getServerSideCommonProps(context);
  522. // check for presence
  523. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  524. if (!('props' in result)) {
  525. throw new Error('invalid getSSP result');
  526. }
  527. const props: Props = result.props as Props;
  528. if (props.redirectDestination != null) {
  529. return {
  530. redirect: {
  531. permanent: false,
  532. destination: props.redirectDestination,
  533. },
  534. };
  535. }
  536. if (user != null) {
  537. props.currentUser = user.toObject();
  538. }
  539. try {
  540. await injectPageData(context, props);
  541. }
  542. catch (err) {
  543. if (err instanceof MultiplePagesHitsError) {
  544. props.isIdenticalPathPage = true;
  545. }
  546. else {
  547. throw err;
  548. }
  549. }
  550. await injectRoutingInformation(context, props);
  551. injectServerConfigurations(context, props);
  552. await injectNextI18NextConfigurations(context, props, ['translation']);
  553. return {
  554. props,
  555. };
  556. };
  557. export default Page;